import 'package:flutter/material.dart';
import 'package:lan_file/utils/log.dart';

import '../utils/udp_socket.dart';

class FindPage extends StatefulWidget {
  final bool isService;
  const FindPage({this.isService = false, super.key});

  final title = '发现';

  @override
  State<FindPage> createState() => _FindPageState();
}

const port = 9999; // 监听的端口号，可根据需要修改

class _FindPageState extends State<FindPage> {
  UdpSocket? socket;
  String socketStatus = '未连接';
  List<SocketMsg> messages = [];

  void msgHandle(UdpSocketEvent<MsgData> event) {
    LogUtil.debugLog('收到来自 ${event.data.sender} 的消息: ${event.data.msg}');
    setState(() {
      messages.add(
        SocketMsg(
          event.data.msg,
          event.data.sender.ip,
          event.data.sender.port,
        ),
      );
    });
  }

  startFind() async {
    // 创建 UDP 套接字并绑定到指定端口
    socket = UdpSocket(
      port: port,
      onReady: () {
        LogUtil.debugLog('正在监听端口 $port 的广播消息...');
        setState(() {
          socketStatus = '正在监听端口 $port 的广播消息...';
        });
      },
      onClose: () {
        LogUtil.debugLog('套接字已关闭');
        setState(() {
          socketStatus = '已关闭';
        });
      },
    );

    // 监听套接字上的数据
    socket?.addEventListener(EventType.msg, msgHandle);
  }

  sendCast() {
    const message = 'hi';
    if (message.isEmpty) return;

    socket?.sendBroadcast(message);
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    socket?.removeEventListener(EventType.msg, msgHandle);
    socket?.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.all(20.0),
              child: Text(
                socketStatus,
              ),
            ),
            Expanded(
              child: SingleChildScrollView(
                child: Column(
                  children: messages.map((msg) {
                    return Text('来自 ${msg.sourceIP}:${msg.sourcePort} 的消息: ${msg.content}');
                  }).toList(),
                ),
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(20.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  ElevatedButton(onPressed: sendCast, child: const Text('发送测试广播')),
                  ElevatedButton(onPressed: startFind, child: const Text('开始监听')),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class SocketMsg {
  String? content;
  String? sourceIP;
  int? sourcePort;
  SocketMsg(this.content, this.sourceIP, this.sourcePort);

  SocketMsg.fromJson(Map<String, dynamic> json) {
    content = json['content'];
    sourceIP = json['sourceIP'];
    sourcePort = json['sourcePort'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['content'] = content;
    data['sourceIP'] = sourceIP;
    data['sourcePort'] = sourcePort;
    return data;
  }
}
